import { director, game, ResolutionPolicy, Scene, SceneAsset, screen, setDisplayStats, Size, sys, TextureCube, view } from "cc";
import { App } from "../App";
import { Singleton, EventConst } from "./Common";

export default class sceneMgr extends Singleton<sceneMgr>{
    private _skyBox:Map<string,TextureCube> = new Map<string,TextureCube>();
    protected onInit(){
        App.Event.on(EventConst.ENTRY_SCENE, this._entryScene, this);
        App.Event.on(EventConst.RESIZE_VIEWPORT, ()=>{
            const size:Size = view.getVisibleSize();
            //screen.windowSize = size;
            view.setResolutionPolicy(size.width > size.height ? ResolutionPolicy.FIXED_HEIGHT : ResolutionPolicy.FIXED_WIDTH);
        }, this);

        App.Event.on(EventConst.SET_SKY_BOX_STYLE,(name:string,useIBL:boolean=true)=>{
            const cub:TextureCube = this._skyBox.get(name);
            const skybox = director.getScene().globals.skybox;
            skybox.enabled = !App.isInvalid(cub);
            if (skybox.enabled){
                skybox.envmap = cub || null;
                skybox.useIBL = useIBL;
            }
        },this);

        setDisplayStats(App.getValue('showFPS'));
        const fps = App.getValue('lockFPS') || 30;
        game.frameRate = fps;
        const design:Size = view.getDesignResolutionSize();
        view.setResolutionPolicy(design.width > design.height ? ResolutionPolicy.FIXED_HEIGHT : ResolutionPolicy.FIXED_WIDTH);

        let paths:string[] = [];
        const cfg = App.getValue('skybox');
        for (let i = cfg.range[0]; i <= cfg.range[1]; ++i){
            paths.push(App.Util.format(cfg.files[1],i));
        }
        App.Asset.waitLoad(paths,(file:string,asset:TextureCube)=>{
            const name:string = file.substring(file.indexOf('Sky_'),file.lastIndexOf('/'));
            this._skyBox.set(name,asset);
        });


        this._initScene('launch');
    }

    private _entryScene(name: string, ...args: any) {
        App.Event.emit(EventConst.LOADING,true);
        if (App.singleScene){
            this._initScene(name);
            App.setMainView(name,args[0],args[1],args[2],args[3],args[4]);
        } else {
            App.Asset.loadScene(App.getValue(`scenes/${name}/name`),(scene:Scene)=>{
                director.runScene(scene);
                setTimeout(() => {
                    this._initScene(name,scene);
                    App.Event.emit(EventConst.LOADING,false);
                }, 1000);
            });
        }
    }

    private _initScene(flag:string,scene?:Scene){
        const cfg:any = App.getValue(`scenes/${flag}`);
        if (App.isInvalid(cfg)){
            throw new Error(`resources/config.json file not set scenes:{${flag}:{...}}`);
        }

        // 背景音乐
        if (cfg.musics.length > 0){
            App.Audio.stop();
            if (cfg.musics.length > 1){
                App.Audio.playGroup(cfg.musics,true);
            } else {
                App.Audio.play(`${cfg.musics[0]}`,false,true);
            }
        }

        !App.Util.isEmpty(cfg.mainView) && App.setMainView(cfg.mainView);
        const newScene:Scene = scene || director.getScene();
        if (cfg['2d']){
            newScene.globals.skybox.enabled = false;
            newScene.globals.fog.enabled = false;
            return ;
        }

        // 设置天空盒
        newScene.globals.skybox.enabled = !App.isInvalid(newScene.globals.skybox.envmap);
    }
}